﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Ya.Orm;

namespace Ya.Router
{
    public static class ProcessorFactory
    {
        public static IHostingEnvironment HostingEnv;
        public static ConnectionConfig ConnConfig = null;
        private static Dictionary<string, Func<RequestEventArgs, string>> processorDic = new Dictionary<string, Func<RequestEventArgs, string>>();
        public static void ProcessRequest(HttpContext context)
        {
            var originalStr = context.Request.Form["OriginalObj"].ToString();
            var originalDic = JObject.Parse(originalStr);
            var resultDic = new Dictionary<string, string>();
            var properties = originalDic.Properties();
            var eventArgs = new RequestEventArgs();            
            eventArgs.Context = context;
            foreach (var property in properties)
            {
                eventArgs.JsonStr = property.Value.ToString();
                var result = processorDic[property.Name](eventArgs);
                resultDic.Add(property.Name, result);
            }
            if (eventArgs.HasDb)
            {
                eventArgs.Db.Dispose();
            }
            var resultStr = JsonConvert.SerializeObject(resultDic);            
            context.Response.WriteAsync(resultStr);
        }
        public static void Init(IHostingEnvironment env)
        {
            HostingEnv = env;
            var types = Assembly.GetEntryAssembly().ExportedTypes;            
            foreach(var t in types)
            {
                if(t.Name.EndsWith("Proc"))
                {
                    var methods = t.GetMethods();
                    foreach(var m in methods)
                    {
                        if (m.IsStatic)
                        {
                            var key = string.Format("{0}.{1}", t.FullName, m.Name);
                            var p = (Func<RequestEventArgs, string>)Delegate.CreateDelegate(typeof(Func<RequestEventArgs, string>), m);
                            processorDic.Add(key, p);
                        }
                    }
                }
            }
        }
    }
}
